import { electronLogger } from "../vendor/electron-logger.ts";
import express from 'express';
import { Server } from 'http';


export default class HttpService {
  private server: Server | null = null;

  async startServer(port: number): Promise<void> {
    return new Promise((resolve, reject) => {
      try {
        const app = express();

        // 添加ping接口
        app.get('/ping', (req, res) => {
          res.json({
            status: 'ok',
            timestamp: new Date().toISOString(),
            message: '服务运行正常'
          });
        });

        this.server = app.listen(port, () => {
          electronLogger.info(`HTTP服务已启动在端口 ${port}`);
          resolve();
        });
      } catch (error) {
        electronLogger.error('启动HTTP服务失败:', error);
        reject(error);
      }
    });
  }

  stopServer(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.server) {
        this.server.close((err) => {
          if (err) {
            electronLogger.error('停止HTTP服务失败:', err);
            reject(err);
          } else {
            electronLogger.info('HTTP服务已停止');
            this.server = null;
            resolve();
          }
        });
      } else {
        resolve();
      }
    });
  }
}


export const httpService = new HttpService()